package com.lagou.rpcclient.lagou.client;

import com.lagou.codec.RpcDecoder;
import com.lagou.codec.RpcEncoder;
import com.lagou.codec.impl.JSONSerializer;
import com.lagou.pojo.RpcRequest;
import com.lagou.pojo.RpcRequestUtil;
import com.lagou.rpcclient.lagou.handler.UserClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 消费者
 */
public class RPCConsumer {

	private static final ExecutorService executorService =
			Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

	private static UserClientHandler userClientHandler;

	public static void initClient() throws InterruptedException {
		userClientHandler = new UserClientHandler();
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(new NioEventLoopGroup())
				.channel(NioSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(new ChannelInitializer<SocketChannel>() {
					protected void initChannel(SocketChannel socketChannel) throws Exception {
						ChannelPipeline pipeline = socketChannel.pipeline();
						pipeline.addFirst(new RpcDecoder(JSONSerializer.getInstance()));
						pipeline.addLast(new RpcEncoder(JSONSerializer.getInstance()));
						pipeline.addLast(userClientHandler);
					}
				});
		bootstrap.connect("127.0.0.1", 8999).sync();
	}


	@SuppressWarnings("unchecked")
	public static <T> T createProxy(Class<? extends T> serviceClass) {
		return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
				new Class[]{serviceClass},
				(Object proxy, Method method, Object[] args) -> {
					final RpcRequest rpcRequest = RpcRequestUtil
							.initRpcRequestByMethodName(serviceClass, method.getName(), args);

					userClientHandler.setRpcRequest(rpcRequest);

					final Future<String> submit = executorService.submit(userClientHandler);

					return submit.get();
				});
	}

}
